
const logApi = `http://log.zhangyy.xyz/p.gif`;

const defaultOptions = {
    et: 'log',
    url: window.location.href,
}

const getStringData = function (data) {
    let ary = [];
    for (let key in data) {
        if (Object.prototype.hasOwnProperty.call(data, key)) {
            let val = data[key];
            if (typeof val === 'object') {
                val = JSON.stringify(val);
            }
            ary.push(`${key}=${encodeURIComponent(val)}`);
        }
    }
    return ary.join('&');
}

const requestLog = (link) => {
    const SEED_NUM = 16777216;
    let img = new Image();
    // 生成随机数，16777216为2的24次方
    let imgId = `img${Math.random() * (SEED_NUM) | 0}`;
    // new Image()赋给全局变量，防止图片请求未建立时，垃圾回收机制回收new Image()，导致请求取消、打点丢失
    window[imgId] = img;
    let cbFn = () => {
        window[imgId] = null;
    };
    img.onload = cbFn;
    img.onerror = cbFn;
    img.src = link;
};

const statistics = {
    sendLog(options) {
        if (!options) {
            throw('日志参数错误');
        }
        if (typeof options === 'string') {
            options = {
                block: options,
            };
        }
        const logData = Object.assign({}, defaultOptions, options);
        const logDataString = getStringData(logData);
        const fullApi = `${logApi}?${logDataString}`;

        requestLog(fullApi);
    },
}

export default statistics;